package com.mgs.tagger.appdata
{
	import com.mgs.tagger.appdata.dto.FileItemDTO;
	import com.mgs.tagger.fsdata.DirectoryScanner;
	import com.mgs.tagger.fsdata.FileTypeExtensions;
	import com.mgs.tagger.log.Level;
	import com.mgs.tagger.log.Logger;
	
	import flash.filesystem.File;

	public class FileItemPictureResolver
	{
		private var item:FileItemDTO;
		public function FileItemPictureResolver(item:FileItemDTO)
		{
			this.item = item;
		}
		public var pictures:Vector.<File>;
		public var videos:Vector.<File>;
		public var indexPicture:int;
		
		public function resolve(root:File):void{
			var files:Vector.<File>;
			if(root.isDirectory){
				Logger.instance.log(Level.INFO, "scan item picture for " + root.name);
				files = new DirectoryScanner().scan(root, FileTypeExtensions.PICTURE_EXTS, true);
				videos = new DirectoryScanner().scan(root, FileTypeExtensions.VIDEO_EXTS, true);
			}else{
				files = new Vector.<File>();
			}
			pictures = files;
			var usedFile:File = null;
			if(item.selectedPictureFilename != null){
				var i:int = 0;
				for each(var fimg:File in files){
					if(fimg.name == item.selectedPictureFilename){
						usedFile = fimg;
						indexPicture = i;
						break;
					}
					i++;
				}
			}
			if(usedFile == null){
				if(files.length == 1){
					Logger.instance.log(Level.INFO, "one picture found for " + root.name);
					usedFile = files[0];
				}else if(files.length > 1){
					Logger.instance.log(Level.INFO, files.length + " pictures found for " + root.name);
					var j:int = 0;
					for each(var ffimg:File in files){
						if(ffimg.name.toLowerCase().indexOf("cover") >= 0){
							usedFile = ffimg;
							break;
						}
						j++;
					}
					if(usedFile == null){
						Logger.instance.log(Level.INFO, "first picture as default for " + root.name);
						usedFile = files[0];
						indexPicture = 0;
					}else{
						Logger.instance.log(Level.INFO, "cover pictures found for " + root.name);
						indexPicture = j;
					}
				}else{
					Logger.instance.log(Level.INFO, "no picture found for " + root.name);
				}
			}
			
		}
		
	}
}